package com.mephi.oshs.model.interpreter.example;

import com.mephi.oshs.model.interpreter.api.IContext;
import com.mephi.oshs.model.interpreter.api.IExpression;

import java.io.Serializable;
import java.util.ArrayList;

public class ContactList implements Serializable {
    private ArrayList<Contact> contacts = new ArrayList<Contact>();

    public ArrayList<Contact> getContacts() {
        return contacts;
    }

    public Contact[] getContactsAsArray() {
        return contacts.toArray(new Contact[1]);
    }

    public ArrayList<Contact> getContactsMatchingExpression(IExpression expr, IContext ctx, Object key) {
        final ArrayList<Contact> results = new ArrayList<Contact>();
        for (final Contact currentElement : contacts) {
            ctx.addVariable(key, currentElement);
            expr.interpret(ctx);
            final Object interpretResult = ctx.get(expr);
            if ((interpretResult != null) && (interpretResult.equals(Boolean.TRUE))) {
                results.add(currentElement);
            }
        }
        return results;
    }

    public void setContacts(ArrayList<Contact> newContacts) {
        contacts = newContacts;
    }

    public void addContact(Contact element) {
        if (!contacts.contains(element)) {
            contacts.add(element);
        }
    }

    public void removeContact(Contact element) {
        contacts.remove(element);
    }

    public String toString() {
        return contacts.toString();
    }
}
